import logging
from django.utils.translation import ugettext as txt
from django.core.urlresolvers import reverse
from django.shortcuts import render_to_response
from django.views.generic.list_detail import object_list
from django.views.generic.create_update import delete_object
from django.http import HttpResponse, Http404, HttpResponseRedirect

from sample.models import Post

def index(request, context={}):
    context['user'] = request.user
    return render_to_response("sample/index.html", context)

def post_index(request, context={}):
    q = Post.objects.all().order_by('-created')

    # Make sure page request is an int. If not, deliver first page.
    try:
        pagenum = int(request.GET.get('page', '1'))
    except ValueError:
        pagenum = 1
    context["title"] = txt('Posts')
    return object_list(request, q, page=pagenum, paginate_by=10, template_name='sample/post_list.html', extra_context=context)

def post_create(request):
    debug('post_create()')
    if request.method == 'POST':
        key = request.POST['key']
        text = request.POST['post_text']
        title = request.POST['post_title']
        
        username = 'Anonymous'
        if request.user and request.user.username:
            username = request.user.username
        debug('username:%s' % username)
        
        if key:
            post = Post.objects.get(pk=key)
            post.updated_by=username
            post.update=True
        else:
            post = Post(created_by=username, updated_by=username)

        post.text = text
        post.title = title
        
        #do save
        new_object = post.save()
        debug('new_object:%s' % new_object)
        
        return HttpResponseRedirect(reverse('sample.views.post_index'))
    else: 
        return HttpResponse(txt("invalid request."))

def post_edit(request, key=None):
    try:
        p = Post.objects.get(pk=key)
    except Post.DoesNotExist:
        raise Http404

    context = {
               'key' : key,
               'post_title' : p.title,
               'post_text' : p.text,
    }
    return post_index(request, context);

def post_delete(request, key=None):
    return delete_object(request, Post, object_id=key,
                         post_delete_redirect=reverse('sample.views.post_index'))

def debug(msg):
    logger = logging.getLogger()
    logger.debug(msg)

